package svc

import (
	"fmt"
	"jgt-oper/src/bll"
	"jgt-oper/src/context"
	"jgt-oper/src/schema"
	"jgt-oper/src/util"
)

// Enterprise 企业管理
type Enterprise struct {
	EnterpriseBll        *bll.Enterprise `inject:""`
	UserBll              *bll.User       `inject:""`
	ParkBll              *bll.Park       `inject:""`
	EntranceEquipmentBll *bll.EEBll      `inject:""`
}

// Get 查询企业信息
func (a *Enterprise) Get(ctx *context.Context) error {
	ctx.WriteOperateLog("Enterprise.Get", "服务平台-企业管理-获取企业信息详情数据")
	user, err := a.UserBll.Get(ctx.GetUserID())
	if err != nil {
		return ctx.ResErrInternalServer(err)
	}
	var enterprise *schema.Enterprise
	if user.EnterpriseID != "" {
		enterprise, err = a.EnterpriseBll.Get(user.EnterpriseID)
		if err != nil {
			return ctx.ResErrInternalServer(err)
		}
	}
	enterpriseMap := util.StructToMap(enterprise)
	var parks = make([]map[int]string, 0)
	allBuildingNodes, err := a.EntranceEquipmentBll.QueryTreeNode()
	if err != nil {
		fmt.Println("数据库查询出错")
	}
	for _, buildingNode := range enterprise.BuildingNodeID {
		var fatherNode string
		fatherNode = buildingNode
		fullName := make(map[int]string)
		for fatherNode != "" {
			for _, nodeDetail := range allBuildingNodes {
				if fatherNode != nodeDetail.RecordID {
					continue
				}
				fullName[nodeDetail.NodeType] = nodeDetail.Name
				if nodeDetail.ParentID != "" {
					fatherNode = nodeDetail.ParentID
					break
				} else {
					fatherNode = ""
				}
			}
		}
		_, ok60 := fullName[60]
		_, ok50 := fullName[50]
		_, ok40 := fullName[40]
		_, ok30 := fullName[30]
		if ok30 && !ok40 {
			fullName[40] = "整栋"
			fullName[50] = "整单元"
			fullName[60] = "整层"
		}
		if ok40 && !ok50 {
			fullName[50] = "整单元"
			fullName[60] = "整层"
		}
		if ok50 && !ok60 {
			fullName[60] = "整层"
		}

		parks = append(parks, fullName)
	}
	enterpriseMap["parks"] = parks
	return ctx.ResSuccess(enterpriseMap)
}

// Update 更新企业信息
func (a *Enterprise) Update(ctx *context.Context) error {
	ctx.WriteOperateLog("Enterprise.Update", "服务平台-企业管理-更新数据")
	var item schema.ServiceUpdateParams
	if err := ctx.ParseJSON(&item); err != nil {
		return ctx.ResErrBadRequest(err)
	}
	err := a.EnterpriseBll.ServiceUpdate(ctx.Param("id"), &item)
	if err != nil {
		return ctx.ResErrInternalServer(err)
	}
	return ctx.ResOK()
}
